<?php

namespace App\Http\Controllers\V1;

use App\Http\Controllers\ApiBaseController;
use App\Models\BalanceLog;
use App\Models\CustomerProduct;
use App\Models\CzOrder;
use App\Models\CzProduct;
use App\Models\CzSpec;
use App\Models\Payment;
use App\Models\SysUser;
use App\Services\CzOrderService;
use EasyWeChat\Factory;
use Illuminate\Database\QueryException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class PayController extends ApiBaseController
{
    protected $payApp;
    protected $baseUrl;
    public function __construct(Request $request)
    {
        $appid = env('appid');
        $mch_id = env('mch_id');
        $this->baseUrl = env('APP_URL');
        $key = env('key');
        $notify_url = env('notify_url');
        parent::__construct($request);
        $config = [
            'app_id' => $appid,
            'mch_id' => $mch_id,
            'key' => $key,
            'cert_path' => base_path(env("cert_path")),
            'key_path' =>  base_path(env("key_path")),
            'notify_url' => $notify_url
        ];
        $this->payApp = Factory::payment($config);
    }
    // 下单接口
    public function createOrder(Request $request)
    {
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $type = $params['type'] ?? 1; //1慢充2快充
        $user_id = $params['user_id'] ?? 25;

        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (!is_numeric($face_value)) {
            return error('面值不正确');
        }
        $mobile_pref = substr($mobile, 0, 7);

        $isp_name = "";
        $city_id = 0;
        $province = "";
        $city = "";
        //获取号码归属地
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $province_id = $area_info->parent_id;
        // 根据面值和运营商获取客户产品
        //获取用户全部产品
        $user = SysUser::find($user_id);
        // 客户的所有面值
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        // 比较价格
        // 获取客户产品
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user->id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {
            // logger($mobile . "没有配置产品" . "订单号：" . $user_order_sn);
            // todo默认产品下单
            // continue;
            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();

        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        // 下单
        $user_price = $user_product->user_price;
        $is_loop = $user_product->is_loop;
        $submit_order_count = $user_product->submit_order_count;
        $user_product_timeout = $user_product->timeout ?? 0;
        $product_info = CzProduct::find($user_product->product_id);
        $spec_info = CzSpec::find($user_product->spec_id);
        $order_sn = 'CZ' . date("YmdH") . sprintf('%04d', $user['id']) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999)) . sprintf('%03d', rand(1, 999));
        $hf_type = 1;
        if ($type == 1) {
            $hf_type = 2;
        } else {
            $hf_type = 1;
        }
        $order_data = [
            "pay_status" => 0,
            "refund_status" => 0,
            'order_sn' => $order_sn,
            "user_order_sn" => $order_sn,
            'product_name' => $product_info->title,
            'mobile' => $mobile,
            'face_value' => $spec_info->face_value,
            'cost' => $user_price,
            'price' => $user_price,
            'area_name' => $province . '-' . $city,
            'province_id' => $province_id,
            'city_id' => $city_id,
            'order_status' => $spec_info->is_cache == 1 ? 5 : 1, //5是压单
            'isp' => $product_info->isp,
            'biz_type' => $product_info->type,
            'hf_type' => $hf_type,
            'product_id' => $product_info->id,
            'spec_id' => $spec_info->id,
            'is_loop' => $is_loop,
            'submit_from' => 'h5',
            'is_auto' => $spec_info->is_auto,
            'submit_order_count' => $submit_order_count ?? env('ORDER_RE_SUBMIT_LIMIT'),
            "callback_url" => "",
            "create_by" => $user->id,
            "update_by" => $user->id,
        ];

        //用户分配产品的超时时间
        if ($user_product_timeout > 0) {
            $order_data['timeout'] = time() + intval($user_product_timeout);
        }
        if (strstr($isp_name, '虚拟') || strstr($isp_name, '物联网')) {
            // 虚拟/物联网-号退
            return error("下单失败,原因:", $isp_name);
        }
        if (strstr($isp_name, '未知')) {
            // 虚拟号退
            return error("下单失败,原因:", $isp_name);
        }

        // 下单成功获取支付参数
        $result = $this->payApp->order->unify([
            'body' => $product_info->title,
            'out_trade_no' => $order_sn,
            'total_fee' => $user_price * 100,
            'spbill_create_ip' => '120.79.232.110', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => env('notify_url'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
        ]);
        $data = [];

        if ($result['return_code'] == "SUCCESS" && $result['result_code'] == 'SUCCESS') {
            // redirect_url=${encodeURIComponent(redirect_url)}
            // 构造重定向
            $redirect_url = env('pay_redirect_url');

            $data['url'] = $result['mweb_url'] . "&redirect_url=" . urlencode($redirect_url . "?order_sn=" . $order_sn);;
            $model = CzOrder::create($order_data);
            return success(["data" => $data]);
        } else {
            return error($result['return_msg']);
        }
    }
    public function payCallbackV2($code, $id)
    {
        logger($code . '|' . $id . "三方支付成功回调" . json_encode(request()->all()));
        $params = request()->all();
        // if ($params['account'] == "39442490880823") {
        //     $id = "jinfu2";
        // }
        $obj = $this->getPayChannelInfoV2($code, $id);
        if (is_string($obj)) {
            return $obj;
        }
        $res = $obj->notifyOrder($params);
        if ($res['code'] != 200) {
            logger("三方支付失败回调notifyOrder" . json_encode($res));
            return "fail" . $res['msg'];
        }
        $order_sn = $res['data']['order_sn'];

        $order_info = CzOrder::where('order_sn', $order_sn)->where('pay_status', 0)->first();
        if (!$order_info) {
            // return error('订单不存在');
            return ['result' => false, 'msg' => "订单不存在"];
        }
        // if (isset($params['account']) && $params['account'] == "36376450209330") {
        //     $pay_type = "jinfu";
        // } else {
        //     $pay_type = "jinfu2";
        // }


        $update_order = [
            "pay_status" => 1,
            "updated_at" => time(),
            "pay_type" => $id
        ];
        logger('修改订单为支付' . $order_info->order_sn);
        // 存在第三方支付订单号则保存
        if (isset($res['data']['pay_order_sn']) && $res['data']['pay_order_sn']) {
            $update_order['pay_order_sn'] = $res['data']['pay_order_sn'];
        }
        $orderUpdateRes = DB::table('cz_order')->where('id', $order_info->id)->update($update_order);
        if (!$orderUpdateRes) {
            return ['result' => false, 'msg' => "通信失败，请稍后再通知我"];
        }
        $user = SysUser::find($order_info->create_by);
        //扣款商户
        // todo验证商户余额
        if ($user->balance + $user->credit < $order_info->price) {
            DB::table('cz_order')->where('id', $order_info->id)->update([
                "order_status" => 5,
                "msg" => "商户余额不足压单",
                "updated_at" => time()
            ]);
            return $res['resp'];
        } else {
            // 扣款商户余额
            DB::transaction(function () use ($user, $order_info) {
                $is_dec_balance = DB::table('sys_users')
                    ->where('id', $user->id)
                    ->where('balance', '>=', ($order_info->price - $user->credit))
                    ->decrement('balance', $order_info->price);
                $balance_log_data = [
                    'order_sn' => $order_info['order_sn'],
                    'money' => $order_info->price,
                    'bf_balance' => $user->balance,
                    'af_balance' => $user->balance - $order_info->price,
                    'bank' => '',
                    'type' => 3,
                    'remark' => "{$order_info->mobile},充值[{$order_info->product_name}{$order_info->face_value}]，消费{$order_info->price}元",
                    'user_id' => $user->id,
                ];
                BalanceLog::create($balance_log_data);
                // 标记订单扣款
                DB::table('cz_order')->where('id', $order_info->id)->update([
                    "plat_status" => 1,
                    // "msg" => "扣除商户余额"
                ]);
            });

            if ($order_info->is_auto == 1 && $order_info->order_status == 1) {
                // 提交订单到队列   
                $temp_str = "";
                if (is_array($res['resp'])) {
                    $temp_str =  json_encode($res['resp']);
                } else {
                    $temp_str = $res['resp'];
                }
                logger($order_sn . $id . '订单处理完成：' . $temp_str);
                sock_queue($order_info->id, 'queue_order');
                return $res['resp'];
            }
        }
        // return "fail" . 'end';
    }
    public function thirdPayCallback($id)
    {
        // var_dump($_POST);
        // $params = array();
        // foreach ($_POST as $key => $val) { //动态遍历获取所有收到的参数,此步非常关键,因为收银宝以后可能会加字段,动态获取可以兼容由于收银宝加字段而引起的签名异常
        //     $params[$key] = $val;
        // }
        // logger(json_encode($params));
        // die;
        logger($id . "三方支付成功回调" . json_encode(request()->all()));
        $params = request()->all();
        // if ($params['account'] == "39442490880823") {
        //     $id = "jinfu2";
        // }
        $obj = $this->getPayChannelById($id);
        $res = $obj->notifyOrder($params);
        if ($res['code'] != 200) {
            logger("三方支付失败回调notifyOrder" . json_encode($res));
            return "fail" . $res['msg'];
        }
        $order_sn = $res['data']['order_sn'];

        $order_info = CzOrder::where('order_sn', $order_sn)->where('pay_status', 0)->first();
        if (!$order_info) {
            // return error('订单不存在');
            return ['result' => false, 'msg' => "订单不存在"];
        }
        // if (isset($params['account']) && $params['account'] == "36376450209330") {
        //     $pay_type = "jinfu";
        // } else {
        //     $pay_type = "jinfu2";
        // }


        $update_order = [
            "pay_status" => 1,
            "updated_at" => time(),
            "pay_type" => $id
        ];
        // 存在第三方支付订单号则保存
        if (isset($res['data']['pay_order_sn']) && $res['data']['pay_order_sn']) {
            $update_order['pay_order_sn'] = $res['data']['pay_order_sn'];
        }
        $orderUpdateRes = DB::table('cz_order')->where('id', $order_info->id)->update($update_order);
        if (!$orderUpdateRes) {
            return ['result' => false, 'msg' => "通信失败，请稍后再通知我"];
        }
        $user = SysUser::find($order_info->create_by);
        //扣款商户
        // todo验证商户余额
        if ($user->balance + $user->credit < $order_info->price) {
            DB::table('cz_order')->where('id', $order_info->id)->update([
                "order_status" => 5,
                "msg" => "商户余额不足压单",
                "updated_at" => time()
            ]);
            return $res['resp'];
        } else {
            // 扣款商户余额
            DB::transaction(function () use ($user, $order_info) {
                $is_dec_balance = DB::table('sys_users')
                    ->where('id', $user->id)
                    ->where('balance', '>=', ($order_info->price - $user->credit))
                    ->decrement('balance', $order_info->price);
                $balance_log_data = [
                    'order_sn' => $order_info['order_sn'],
                    'money' => $order_info->price,
                    'bf_balance' => $user->balance,
                    'af_balance' => $user->balance - $order_info->price,
                    'bank' => '',
                    'type' => 3,
                    'remark' => "{$order_info->mobile},充值[{$order_info->product_name}{$order_info->face_value}]，消费{$order_info->price}元",
                    'user_id' => $user->id,
                ];
                BalanceLog::create($balance_log_data);
                // 标记订单扣款
                DB::table('cz_order')->where('id', $order_info->id)->update([
                    "plat_status" => 1,
                    // "msg" => "扣除商户余额"
                ]);
            });

            if ($order_info->is_auto == 1 && $order_info->order_status == 1) {
                // 提交订单到队列   
                logger($order_sn . $id . '订单处理完成：' . $res['resp']);
                sock_queue($order_info->id, 'queue_order');
                return $res['resp'];
            }
        }
        // return "fail" . 'end';
    }
    protected function getPayChannelInfoV2($code, $id)
    {
        $payment_info = Payment::find($id);
        if (!$payment_info) {
            return "error";
        }
        $obj = $this->getPayChannelByIdV2($id);
        return $obj;
    }
    protected function getPayChannelByIdV2($pay_channel_id, $type = "cz")
    {
        $channel_info = Payment::find($pay_channel_id);
        $setting_arr = $channel_info->setting;
        $setting = [];
        foreach ($setting_arr as $v) {
            $setting[$v['name']] = $v['val'];
        }
        $setting['channel_code'] = $channel_info->payment_code;
        $setting['channel_id'] = $pay_channel_id;
        $setting['callback_url'] = $channel_info->callback_url;
        $temp_file = $channel_info->file_path ?? $channel_info->channel_code;
        $channel_file = base_path("payChannel/" . $temp_file . ".php");
        include_once $channel_file;
        // dd($setting);
        $obj = new $channel_info['payment_code']($setting);
        return $obj;
    }
    protected function getPayChannelById($id)
    {
        if ($id == "tlhsb_yc") {
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb_yc";
            $setting = config('pay')['tlhsb_yc'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "tlhsb_yc_1YJT") {
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb_yc_1YJT";
            $setting = config('pay')['tlhsb_yc_1YJT'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "tlhsb") {
            $channel_file = base_path("payChannel/tlhsb/" . "tlhsb.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/tlhsb";
            $setting = config('pay')['tlhsb'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "tlhsb";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "jinfu") {
            $channel_file = base_path("payChannel/jinfu/" . "jinfu.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/jinfu";
            $setting = [
                "account" => env('third_account'),
                "key" => env('third_key'),
                "callback_url" => $callback_url,

            ];
            $payClassName = "jinfu";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "jinfu2") {
            $channel_file = base_path("payChannel/jinfu/" . "jinfu.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/jinfu2";
            $setting = [
                "account" => env('third_account2'),
                "key" => env('third_key2'),
                "callback_url" => $callback_url,
            ];
            $payClassName = "jinfu";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "huilian_022" || $id == "huifu_022") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian_022";
            $setting = config('pay')['huilian_022'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "huilian_022_si" || $id == "huifu_022_si") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian_022_si";
            $setting = config('pay')['huilian_022_si'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "huilian" || $id == "huifu") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian";
            $setting = config('pay')['huilian'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "huifu_yxwy") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huifu_yxwy";
            $setting = config('pay')['huifu_yxwy'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian";
            $obj = new $payClassName($setting);
            return $obj;
        }
        // 严选快享小程序
        if ($id == "huifuYxkx" || $id == "huifuYxkx") {
            $channel_file = base_path("payChannel/huilian/" . "huilian.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huifuYxkx";
            $setting = config('pay')['huilian'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian";
            $obj = new $payClassName($setting);
            return $obj;
        }
        // 严选快享小程序汇旺财
        if ($id == "hstyYXkx") {
            $channel_file = base_path("payChannel/hsty/" . "hsty.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/hstyYXkx";
            $setting = config('pay')['hstyYXkx'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "hsty";
            $obj = new $payClassName($setting);
            return $obj;
        }
        if ($id == "huifu2" || $id == "huilian2") {
            $channel_file = base_path("payChannel/huilian2/" . "huilian2.php");
            include_once $channel_file;
            $callback_url = env("third_notify_url") . "/huilian2";
            $setting = config('pay')['huilian2'];
            $setting['callback_url'] = $callback_url;
            $payClassName = "huilian2";
            $obj = new $payClassName($setting);
            return $obj;
        }
    }
    public function payCallback()
    {
        logger("微信支付成功回调" . json_encode(request()->all()));
        $response = $this->payApp->handlePaidNotify(function ($message, $fail) {
            // 你的逻辑
            $order_sn = $message['out_trade_no'];
            // {"appid":"wxb8d24efd63d9b137","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"Y","mch_id":"1640696405","nonce_str":"650e571562b1c","openid":"oX0Bw59hr3KSiZdU4VFMHVBu2eVY","out_trade_no":"1695438613","result_code":"SUCCESS","return_code":"SUCCESS","sign":"05341FDFA75B8B2EB0222D80D3D655A9","time_end":"20230923111022","total_fee":"1","trade_type":"MWEB","transaction_id":"4200001907202309233083641541"}  
            logger('handlePaidNotify-message' . json_encode($message));
            if ($message['return_code'] === 'SUCCESS' && $message['result_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                //充值业务类型订单
                // $ret = $this->czOrder($order_sn);
                $order_info = CzOrder::where('order_sn', $order_sn)->where('pay_status', 0)->first();
                if (!$order_info) {
                    logger('订单未找到或者已支付:' . $order_sn);
                    return $fail('通信失败，请稍后再通知我');
                    // return ['result' => true, 'msg' => '订单未找到或者已支付'];
                }
                $res = DB::table('cz_order')->where('id', $order_info->id)->update([
                    "pay_status" => 1,
                    "updated_at" => time(),
                    "pay_type" => "wx"
                ]);
                if (!$res) {
                    return $fail('通信失败，请稍后再通知我');
                }
                $user = SysUser::find($order_info->create_by);

                //扣款商户
                // todo验证商户余额
                if ($user->balance + $user->credit < $order_info->price) {
                    DB::table('cz_order')->where('id', $order_info->id)->update([
                        "order_status" => 5,
                        "msg" => "商户余额不足压单",
                        "updated_at" => time()
                    ]);
                } else {
                    // 扣款商户余额
                    DB::transaction(function () use ($user, $order_info) {
                        $is_dec_balance = DB::table('sys_users')
                            ->where('id', $user->id)
                            ->where('balance', '>=', ($order_info->price - $user->credit))
                            ->decrement('balance', $order_info->price);
                        $balance_log_data = [
                            'order_sn' => $order_info['order_sn'],
                            'money' => $order_info->price,
                            'bf_balance' => $user->balance,
                            'af_balance' => $user->balance - $order_info->price,
                            'bank' => '',
                            'type' => 3,
                            'remark' => "{$order_info->mobile},充值[{$order_info->title}]，消费{$order_info->price}元",
                            'user_id' => $user->id,
                        ];
                        BalanceLog::create($balance_log_data);
                        // 标记订单扣款
                        DB::table('cz_order')->where('id', $order_info->id)->update([
                            "plat_status" => 1,
                            // "msg" => "扣除商户余额"
                        ]);
                    });
                    if ($order_info->is_auto == 1 && $order_info->order_status == 1) {
                        // 提交订单到队列   
                        logger($order_sn . '订单处理完成');
                        sock_queue($order_info->id, 'queue_order');
                        return true;
                    }
                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }
            // 或者错误消息
            $fail('Order not exists.');
        });
        return $response->send();
    }
    // 回调中退款
    public function refund(Request $request)
    {
        $params = $request->all();
        $pwd = $params['pwd'];
        $msg = $params['order_remark'];
        $id = $params['order_id'];
        if ($pwd !== "774896") {
            return error('失败');
        }
        $order_info = CzOrder::where([
            "pay_status" => 1,
            "refund_status" => 0,
        ])->find($id);
        if (!$order_info) {
            return error('失败');
        }
        (new CzOrderService())->refund($order_info, $msg);
        return success();
    }
    // 退款
    public function refundOrder(Request $request)
    {
        $params = $request->all();
        $ids = $params['ids'];
        if (!isset($params['ids']) || !isset($params['password'])) {
            return error('参数错误');
        }
        $user_pwd = $request->post('password', '');
        $user = auth()->user();
        if (Hash::check($user_pwd, $user->password) == false) {
            return error('密码有误');
        }
        $msg = substr($request->post('remark'), 0, 100);


        $order_info = CzOrder::whereIn('id', $ids)
            ->whereIn('refund_status', [0, 2])->where([
                "pay_status" => 1
            ])->get();
        if (!$msg) {
            $msg = "失败";
        }
        $czService = new CzOrderService();
        $errMsg = "";
        foreach ($order_info as $key => $value) {

            $res = $czService->refund($value, $msg);
            if (!$res['result']) {
                $errMsg .= $value->mobile . '退款失败:原因:' . $res['msg'];
            }
        }
        if ($errMsg) {
            return error($errMsg);
        }
        return success();
    }
    public function getPayParams()
    {
        // 获取支付参数
        $channel_file = base_path("payChannel/hsty/" . "hsty.php");
        $callback_url = env("third_notify_url") . "/hstyYXkx";
        include_once $channel_file;
        // $rsaPrivateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCbCu1P05TRBHGbOsXS0UhLvXoQ12u4sy8ugHOZpt/+/pQWZU4P3mxR1ogGzX3Lb6TzYqtlKnMVkAyL5THLlcA+yhrARkQyqcJ5pKVBUr1FvZrHzbSsWcaO0Spbft/lDb2Nha37DcuTpmfbMPuKaRRUpswbvJvQxiaJT9TRTt5AsdPb1vYJ7G0Kvxj5TdJ2TWLMDkp/2cVUxCC8egxADuGtUcxIkxTvCv+Wgnj4BJEgrFtUsW4nmATQpJ8Y3NGgTf3cjMoHi27JRyFgHok365YrjAMWFy1ThM+vFHU0FDvWYJavdsHi0O66WLqdJeUc3lQaEFDXcyn526Nmt0kzpN85AgMBAAECggEAYEG4dAb4LYyEu8sRZoFoUR2h2zLjPhiBAm3dV1ezWazUY9MhU9jThzuZ2B9cKiF2V2S65GQmbwyvvWreL3cZk+IGGbmGPa4Hf14o+xVTTSkaH1InC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ZJCOe0RFjnj9dfLJXJdPG8p46DInN+y3aNV";
        // $rsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmwrtT9OU0QRxmzrF0tFIS716ENdruLMvLoBzmabf/v6UFmVOD95sUdaIBs19y2+k82KrZSpzFZAMi+Uxy5XAPsoawEZEMqnCeaSlQVK9Rb2ax820rFnGjtEqW37f5Q29jYWt+w3Lk6Zn2zD7imkUVKbMG7yb0MYmiU/U0U7eQLHT29b2CextCr8Y+U3Sdk1izA5Kf9nFVMQgvHoMQA7hrVHMSJMU7wr/loJ4+ASRIKxbVLFuJ5gE0KSfGNzRoE393IzKB4tuyUchYB6JN+uWK4wDFhctU4TPrxR1NBQ71mCWr3bB4tDuuli6nSXlHN5UGhBQ13Mp+dujZrdJM6TfOQIDAQAB";
        $set = config('pay')['hstyYXkx'];
        $submitData = [
            'OutTradeNo' => time(),
            'Body' => '测试支付',
            'TotalAmount' => 100,
            'OpenId' => "opkSO61vy8Lw5uMHnjGXV9INAaEQ",
            'SubAppId' => "wxaeda8fa3fb79039e",
            "success_back_page" => ""
        ];
        $set['callback_url'] = $callback_url;
        $payClassName = "hsty";
        $obj = new $payClassName($set);
        $res = $obj->submitOrder($submitData);
        // var_dump($res);
        return success(['data' => $res['payInfo']]);
        // $channel_file = base_path("payChannel/huilian2/" . "huilian2.php");
        // include_once $channel_file;
        // $callback_url = env("third_notify_url") . "/huifu2";
        // $rsaPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAs/mLoolalaxPQJAZvMg9ajCPwdhqJzIBxQQ0i6D1ch56Y/3DMn7KB1yeR5aMJjrzFA66aW+CM266CXF8s0vAQmXkCxpDVsSyYHliatIVJOJupxGCPUAwsjz3QLkkxZVaNfxqeyLhfdZ4ES2xJVWCfAf4hLop6G641mwzgwbjkptGG4fhzhqpLRXlHN98wXpDxaEb6WJdvLOWWSl+gu3I4bEcNawjnnO+hIBK96dVMA7m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flHIHb7/qFFr/H2Ecc1r04neW+Y4S/Fh4TMD0bH/61CDH3KFbktc2L2YysonQxd1nZ/5W0IibTaGvss8rOHbvW+tqjuna4YTkvQxJlh5KVoJaK+kbIO2slVtb4qET/jPOGn9HRyQwKBgQDj1BVEFVStKiuhDaJiMo5vVme60Hfk61SC7GqyFzD6K8CBTfm0PKnpYBxmqkaWKY2ZPw3L06ZU2yOHkzkEla4Az5tH1ybBxEPcmp4p8ZdQBrDo+YjHX7J9NHnXpc1J0bs03si32lq1eDWMvVMrDFmxzXkpfzyq1MDqVsUF5ntw8QKBgC9gmQ+FvOQAkAmQYi4y6fAQSUCbKIT5ycmYVpK3lOasFyDUdEhA6E/2bOPgwZ+2QJJwkx+/5WqEGSXxgfznx+I2yKy7hMDvkDmD2w3l6h0+EvfDx9WtNJhlmfosVGqI0F/i5llB6FyZ4FkvXsctcbCa7v6ksz8NjEEiFme7+d6XAoGBAJQeAVlefm3CJf/g45jLPMvvWuku5EnGRPzlH4Flfo+YyWdYB+g0BC2h+F/08r6AXrNhDb0Za+W4c7tOTD4IoEyXMPsa89xwu0sUdRe6V9VlDPHwirPtx75/IQ/Tz07CZTxkdmB2VjeHyDnCcOaCPKHspDe6PImCgiB8iDkYSSmH";
        // $sys_id = "6666000144295701";
        // $product_id = "EDUARK";
        // $submitData = [
        //     'OutTradeNo' => time(),
        //     'Body' => '充值支付',
        //     'TotalAmount' => 100,
        //     'OpenId' => "opkSO61vy8Lw5uMHnjGXV9INAaEQ",
        //     'SubAppId' => "wxff3e969d7c6364f9",
        //     "success_back_page" => ""
        // ];
        // $payClassName = "huilian2";
        // $obj = new $payClassName([
        //     "rsaPrivateKey" => $rsaPrivateKey,
        //     "rsaPublicKey" => $rsaPublicKey,
        //     "sys_id" => $sys_id,
        //     "product_id" => $product_id,
        //     "callback_url" => $callback_url,
        // ]);

        // $res = $obj->submitOrder($submitData);
        // // $res = $obj->refund($sub)
        // return success(['data' => $res['payInfo']]);
        // $result = $this->payApp->order->unify([
        //     'body' => '腾讯充值中心-QQ会员充值',
        //     'out_trade_no' => time(),
        //     'total_fee' => 1,
        //     'spbill_create_ip' => '120.79.232.110', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
        //     'notify_url' => $this->baseUrl . '/api/payCallback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
        //     'trade_type' => 'MWEB', // 请对应换成你的支付方式对应的值类型
        // ]);
        // $data = [];
        // if ($result['result_code'] == "SUCCESS" && $result['return_code'] == 'SUCCESS') {
        //     $data['url'] = $result['mweb_url'];
        //     return success(["data" => $data]);
        // } else {
        //     return error($result['return_msg']);
        // }
    }
    public function getBanner(Request $request)
    {

        return success([
            "data" => [
                // "http://120.79.232.110/storage/img1.jpg",
                // $this->baseUrl . "/storage/img1.jpg",
                $this->baseUrl . "/storage/tip1.jpg",
                $this->baseUrl . "/storage/tip2.jpg",
                // "http://120.79.232.110/storage/goods3.jpg",
                // "http://120.79.232.110/storage/goods4.jpg",
                // "http://120.79.232.110/storage/goods5.jpg",
            ]
        ]);
    }
    // 根据手机号查询运营商
    public function getIspBymobile(Request $request)
    {
        $params = $request->all();
        $mobile = $params['mobile'] ?? '';
        $face_value = intval($params['face_value'] ?? '100'); //面值
        if (!$mobile) {
            return success();
        }
        if (!is_numeric($mobile)) {
            return error('手机号码格式有误');
        }
        if (strlen($mobile) != 11) {
            return success();
        }
        $mobile_pref = substr($mobile, 0, 7);
        $mobile_info = DB::table('phone')->where('phone', $mobile_pref)->first();
        if (!$mobile_info) {
            return error('归属地查询失败,请仔细核对号码！');
        }
        $city_id = 0;
        $province = "";
        $city = "";
        $isp_name = "";
        $city_id = $mobile_info->area_code;
        $isp_name = $mobile_info->isp;
        $province = $mobile_info->province;
        $city = $mobile_info->city;
        if (strpos($city_id, '/') !== false) {
            $city_id_exp = explode("/", $city_id);
            $city_id = $city_id_exp[0];
        }
        $area_info = DB::table('areas')->where('id', $city_id)->first();
        if (!$area_info) {
            return error('地区信息不存在');
        }
        $isp = 0;
        switch ($isp_name) {
            case '移动':
                $isp = 1;
                break;
            case '移动/虚拟':
                $isp = 1;
                break;
            case '移动/物联网':
                $isp = 1;
                break;
            case '移动/未知':
                $isp = 1;
                break;
            case '联通':
                $isp = 2;
                break;
            case '联通/虚拟':
                $isp = 2;
                break;
            case '联通/物联网':
                $isp = 2;
                break;
            case '电信':
                $isp = 3;
                break;
            case '广电':
                $isp = 3;
                break;
            case '电信/虚拟':
                $isp = 3;
                break;
            case '电信/物联网':
                $isp = 3;
                break;
        }
        $user_id = 25;
        $province_id = $area_info->parent_id;
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_province_id' => $province_id,
            'mobi_city_id' => $city_id,
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->where('status', 1)->whereIn('product_id', $product_id)->pluck('id');
        $user_product = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->with(['channels'])->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->get();
        if (count($user_product->toArray()) == 0) {

            return error('没有分配产品');
        }
        $temp_arr = $user_product->toArray();
        $cur_user_product_id = $temp_arr[0]['id'];
        foreach ($temp_arr as $key => $val) {
            $product_id = $val['product_id'];
            $prodcut = CzProduct::find($product_id);
            if ($prodcut->city_id) {
                // 分市
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分市');
                break;
            } else if ($prodcut->province_id) {
                // 分省
                $cur_user_product_id = $val['id'];
                logger('mobile' . $mobile . ',cur_user_product_id' . $cur_user_product_id . '分省');
                break;
            }
        }
        $user_product = CustomerProduct::find($cur_user_product_id);
        $user_price = $user_product->user_price;
        // CustomerProduct::where('user_id',$user_id)->where([
        //     ""
        // ])
        // $baseUrl = env('APP_URL');
        $face_img = $this->baseUrl . "/storage/yd_100.jpg";
        if ($face_value == 100) {
            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/yd_100.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_100.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_100.jpg";
            }
        }
        if ($face_value == 200) {
            if ($isp == 1) {
                $this->baseUrl . "/storage/yd_200.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_200.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_200.jpg";
            }
        }

        $mobile_info->price = $user_price;
        $mobile_info->face_img = $face_img;
        return success([
            "data" => $mobile_info
        ]);
    }
    public function getDetailImg(Request $request)
    {

        return success([
            "data" => $this->baseUrl . "/storage/banner1.jpg",
        ]);
    }
    public function getDescInfo(Request $request)
    {
        $type = $request['type'] ?? 1;  //1慢充2快充
        $isp = $request['isp'] ?? 1;  //1移动2联通3电信

        $face_value = intval($request['face_value'] ?? 100);  //1移动2联通3电信
        if (!is_numeric($face_value)) {
            // return error('面值不正确');
            $face_value = 100;
        }
        if ($isp == 4) {
            $isp = 3;
        }
        // $slow_discount = "0.96"; //慢充折扣
        // 获取慢充折扣
        $user_id = 25;
        $slow_discount = "0.95";
        $user_id = $params['user_id'] ?? 25;
        $user_spec_id = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->pluck('spec_id');
        $product_id = CzProduct::filter([
            'mobi_spec_id' => $user_spec_id,
            'isp' => $isp
        ])->pluck('id');
        $spec_id = CzSpec::where('face_value', $face_value)->whereIn('product_id', $product_id)->where('status', 1)->pluck('id');
        $info = CustomerProduct::filter(
            [
                'user_id' => $user_id,
                'isp' => $isp
            ]
        )->whereIn('spec_id', $spec_id)->orderBy('user_price', 'asc')->first();
        if (!$info) {
            logger('isp' . $isp . 'face_value' . $face_value);
        }
        $user_price = $info->user_price;
        $face_img = $this->baseUrl . "/storage/yd_100.jpg";
        // $face_img = $this->baseUrl . "/storage/f_100.jpg";
        if ($user_price / 100  > 0.50) {
            // 100面值
            $slow_discount = $user_price / 100;

            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/yd_100.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_100.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_100.jpg";
            }
        }
        if ($user_price / 100  < 0.50) {
            $slow_discount = $user_price / 100 * 2;
            $face_img = $this->baseUrl . "/storage/f_50.jpg";

            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/yd_50.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_50.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_50.jpg";
            }
        }
        if ($user_price / 100  > 1.50) {
            $slow_discount = $user_price / 100 / 2;
            // $face_img = $this->baseUrl . "/storage/face_value_100.jpg";
            if ($isp == 1) {
                $face_img = $this->baseUrl . "/storage/yd_200.jpg";
            }
            if ($isp == 2) {
                $face_img = $this->baseUrl . "/storage/lt_200.jpg";
            }
            if ($isp == 3) {
                $face_img = $this->baseUrl . "/storage/dx_200.jpg";
            }
        }



        $fast_dicount = "0.998"; //快充折扣
        //    <p style="font-size: 12px;margin-top:7px">【售后时间】09:00~22:00（每天）</p>
        //    <p style="font-size: 12px;margin-top:7px">【客服电话】0769-2288 8969</p>
        // <span style="color:#f00;">充值类型为慢充</span>
        $rich = '<p style="color:#858585;">温馨提示：</p>
        <div style="font-size: 12px;margin-top:5px;color:#858585;">
            <p style="font-size: 12px;margin-top:5px">1.携号转网号码、副卡号码或运营商黑名单号码（长期欠费或非实名认证）无法完成充值，请勿下单。</p>
            <p style="font-size: 12px;margin-top:5px">2.下单前请核对号码及对应运营商，下单后充值的订单无法撤销，充值成功后订单不支持退款。</p>
            <p style="font-size: 12px;margin-top:5px">3.72小时内到账，急用勿充，到账有时会分批到账。</p>
            <p style="font-size: 12px;margin-top:5px">4.本平台暂不提供开票服务，发票一般由运营商提供。你可以到当地营业厅打印发票，或登录网上营业厅下载电子发票，具体政策请咨询对应的运营商。</p>
        </div>';

        return success([
            "data" => [
                "title" => "【充值过程中请勿再通过其他渠道下单】",
                "tip" => "订单售后周期为订单完成后30天，超时不予处理",
                "rich" => $rich,
                "contact" => "人工客服：4001588569（09:00-22:00）",
                "slow_discount" => $slow_discount,
                "fast_discount" => $fast_dicount,
                "face_img" => $face_img,
                "user_price" => $user_price

            ]
        ]);
    }
    public function getOrderList(Request $request)
    {
        $params = $request->all();
        if (!isset($params['mobile'])) {
            return error('fail');
        }
        $paginator = CzOrder::filter($params)->where('pay_status', 1)->orderBy("id", 'desc')->paginate($this->pageSize);
        return success(page_format($paginator));
    }
    public function getImgList(Request $request)
    {
        $list = [];
        return success([
            "data" => $list
        ]);
    }
    public function getOrderInfo(Request $request)
    {
        $order_sn = request('order_sn');
        if (!$order_sn) {
            return error('fail');
        }
        $order =  CzOrder::where('order_sn', $order_sn)->where('pay_status', 1)->first();
        if ($order) {
            return success([
                "data" => true
            ]);
        } else {
            return success([
                "data" => false
            ]);
        }
    }
}
